<template>
  <div class="alarm-record-container">
    <el-card shadow="never" class="mb-5 border-box">
      <div class="filter-section">
        <div class="left-section">
          <div class="search-box">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索报警位置"
              class="search-input"
              :prefix-icon="Search"
              clearable
              @input="handleSearch"
            />
          </div>
        </div>
      </div>
    </el-card>
    <div class="page-content alarm-list">
      <el-table
        v-loading="isLoading"
        :data="alarmList"
        class="w-full"
        v-if="!showEmpty"
        height="calc(100vh - 328px)"
      >
      <el-table-column prop="userName" label="报警人员" min-width="180" />
      <el-table-column prop="phone" label="报警人联系方式" min-width="180" />
        <el-table-column prop="alarmTime" label="报警时间" min-width="150">
          <template #default="scope">
            {{ scope.row.alarmTime ? useDateFormat(scope.row.alarmTime, 'YYYY-MM-DD HH:mm:ss').value : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="alarmDescription" label="报警简要描述" min-width="120" />
        <el-table-column prop="location" label="报警位置" min-width="180" />
        <el-table-column prop="status" label="处理状态" min-width="100">
          <template #default="scope">
            <el-tag
              :type="getFeedbackStatusColor(FeedbackStatusMaps[parseInt(scope.row.status) - 1])"
              effect="light"
            >
              {{ FeedbackStatusMaps[parseInt(scope.row.status) - 1] }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="handleResult" label="处理说明/结论" min-width="120" />
        <el-table-column prop="handleTime" label="处理完成时间" min-width="120">
          <template #default="scope">
            {{ scope.row.handleTime ? useDateFormat(scope.row.handleTime, 'YYYY-MM-DD HH:mm:ss').value : '' }}
          </template>
        </el-table-column> -->
        <el-table-column fixed="right" label="操作" width="160px">
          <template #default="scope">
            <el-row>
              <el-button
                type="primary"
                text
                size="small"
                link
                @click="showDetailDialog(scope.row)"
              >
                <el-icon><View /></el-icon>
                详情
              </el-button>
              <el-button
                v-if="scope.row.status == 1"
                type="success"
                text
                size="small"
                link
                @click="handleAlarm(scope.row)"
              >
                <el-icon><Tools /></el-icon>
                处理
              </el-button>
            </el-row>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态 -->
      <div class="flex justify-center h-[calc(100vh-328px)]" v-if="showEmpty">
        <el-empty description="暂无报警记录" />
      </div>

      <!-- 分页器 -->
      <div class="flex justify-center mt-5">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :hide-on-single-page="false"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 详情弹窗 -->
      <el-dialog v-model="detailDialogVisible" title="报警详情" width="50%">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="报警人员">{{ currentRecord.touristUserVo?.userName }}</el-descriptions-item>
          <el-descriptions-item label="报警人联系方式">{{ currentRecord.phone }}</el-descriptions-item>
          <el-descriptions-item label="报警时间">
            {{ currentRecord.alarmTime ? useDateFormat(currentRecord.alarmTime, 'YYYY-MM-DD HH:mm:ss').value : '' }}
          </el-descriptions-item>
          <el-descriptions-item label="报警简要描述">{{ currentRecord.alarmDescription }}</el-descriptions-item>
          <el-descriptions-item label="报警位置">{{ currentRecord.location }}</el-descriptions-item>
          <el-descriptions-item label="处理状态">
            {{ currentRecord.status ? FeedbackStatusMaps[parseInt(currentRecord.status) - 1] : '' }}
          </el-descriptions-item>
          <el-descriptions-item label="处理人">{{ currentRecord.userVo?.usrName }}</el-descriptions-item>
          <el-descriptions-item label="处理说明/结论" v-if="currentRecord.status !== 1">
            {{ currentRecord.handleResult }}
          </el-descriptions-item>
          <el-descriptions-item label="处理时间" v-if="currentRecord.status !== 1">
            {{ useDateFormat(currentRecord.handleTime, 'YYYY-MM-DD HH:mm:ss').value }}
          </el-descriptions-item>
        
        </el-descriptions>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="detailDialogVisible = false">关闭</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 处理弹窗 -->
      <el-dialog v-model="handleDialogVisible" title="处理报警" width="50%">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="处理状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择处理状态">
              <el-option
                v-for="(status, index) in FeedbackStatusMaps"
                :key="index"
                :label="status"
                :value="index + 1"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="处理说明/结论" prop="handleResult">
            <el-input
              v-model="form.handleResult"
              type="textarea"
              :rows="4"
              placeholder="请输入处理说明/结论"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="handleDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitHandle(formRef)">确认</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { Search, View, Check } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useDateFormat } from '@vueuse/core'
import { AlarmRecord } from '@/api/4a/types'
import { AlarmStatusEnum } from '@/types/alarmRecord'
import {
  alarmPageUsingPost,
  alarmGetUsingGet,
  alarmUpdateStatusUsingPost
} from '@/api/4a/jingbaoguanli'
import { useUserStore } from '@/store/modules/user'
const userStore = useUserStore()
const userInfo = computed(() => userStore.getUserInfo)
const alarmList = ref<any>([])
const total = ref(0)
const isLoading = ref(true)
const currentPage = ref(1)
const searchKeyword = ref('')
const pageSize = ref(10)
const detailDialogVisible = ref(false)
const handleDialogVisible = ref(false)
const currentRecord = ref<any>({})
const formRef = ref<FormInstance>()

const form = reactive({
  id: '' as string | number,
  handleResult: '',
  status: '',
  handleTime: '',
  handlerUserId: '',
})

const rules = reactive({
  handleResult: [{ required: true, message: '请输入处理结果', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
})

// 请求参数
const queryParams = computed(() => {
  return {
    current: currentPage.value,
    size: pageSize.value,
    alarmLocation: searchKeyword.value
  }
})

// 是否显示空状态
const showEmpty = computed(() => {
  return !isLoading.value && (!alarmList.value || alarmList.value.length === 0)
})
// 状态类型
const FeedbackStatusMaps = Object.keys(AlarmStatusEnum).map(
    (key) => AlarmStatusEnum[key as keyof typeof AlarmStatusEnum]
  )
 // 获取反馈状态颜色
 const getFeedbackStatusColor = (state: string) => {
  switch (state) {
    case AlarmStatusEnum.PENDING:
      return 'danger'
    case AlarmStatusEnum.PROCESSING:
      return 'warning'
    case AlarmStatusEnum.REPLIED:
      return 'success'
    case AlarmStatusEnum.CLOSED:
      return 'info'
    default:
      return undefined
  }
}
// 获取报警记录列表
const getAlarmList = async () => {
  isLoading.value = true
  try {
    const res = await alarmPageUsingPost({
      body: queryParams.value
    })
    if (res.code === 0) {
      alarmList.value = res.data?.list || []
      total.value = res.data?.total || 0
    } else {
      ElMessage.error('获取报警记录列表失败')
    }
  } catch (error: any) {
    console.log(error)
    ElMessage.error('获取报警记录列表失败')
  } finally {
    isLoading.value = false
  }
}

// 获取报警记录详情
const getAlarmDetail = async (id: string | number) => {
  try {
    const res = await alarmGetUsingGet({ params: { id } })
    if (res.code === 0) { 
      currentRecord.value = res.data || {}
    } else {
      ElMessage.error('获取报警记录详情失败')
    }
  } catch (error: any) {
    console.log(error)
    ElMessage.error('获取报警记录详情失败')
  }
}

// 处理报警
const handleAlarm = (row: AlarmRecord) => {
  handleDialogVisible.value = true
  form.id = row.id
  form.handleResult = ''
  form.handlerUserId = userInfo.value.id
}

// 提交处理
const submitHandle = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        const res = await alarmUpdateStatusUsingPost({
          body: {
            id: form.id,
            status: form.status,
            handleResult: form.handleResult,
            handleTime: useDateFormat(Date.now(), 'YYYYMMDDHHmmss').value,
            handlerUserId: form.handlerUserId
          }
        })
        if (res.code === 0) {
          ElMessage.success('处理成功')
          handleDialogVisible.value = false
          getAlarmList()
        } else {
          ElMessage.error('处理失败')
        }
      } catch (error: any) {
        console.log(error)
        ElMessage.error('处理失败')
      }
    }
  })
}

// 显示详情
const showDetailDialog = async (row: AlarmRecord) => {
  detailDialogVisible.value = true
  await getAlarmDetail(row.id)
}

// 处理页码大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  getAlarmList()
}

// 分页切换
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getAlarmList()
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getAlarmList()
}

onMounted(() => {
  getAlarmList()
})
</script>

<style scoped>


.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input {
  width: 300px;
}
</style>